package com.yjd.pub.bank.service;

import com.yjd.comm.annotation.Cacheable;
import com.yjd.comm.bank.dto.BankInfoDto;
import com.yjd.comm.bank.model.AuthBankModel;
import com.yjd.comm.bank.model.BankCardDataModel;
import com.yjd.comm.bank.model.BankHistoryModel;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.credit.model.CreditLineApplyModel;
import com.yjd.comm.credit.service.ICreditLineApplyService;
import com.yjd.comm.enums.ExpireTime;
import com.yjd.comm.enums.GenderEnum;
import com.yjd.comm.enums.OrderStatusEnum;
import com.yjd.comm.fundservice.util.QianKangServer;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.user.model.UserDataModel;
import com.yjd.comm.user.service.IUserDataService;
import com.yjd.comm.util.AuthBankUtils;
import com.yjd.comm.util.CardNoUtils;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant;
import com.yjd.pub.bank.dao.IBankDao;
import com.yjd.pub.bank.dao.IBankHistoryDao;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * <b>description</b>：用户银行卡业务实现<br>
 * <b>time</b>：2017-06-26 13:25:47 <br>
 * <b>author</b>：  yangchangyan@yijiedai.com
 */
@Service("bankService")
public class BankServiceImpl extends BaseServiceImpl implements IBankService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public BankModel insert(BankModel model) throws Exception {
		return this.bankDao.insertModel(model, true);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(BankModel model) throws Exception {
		return this.bankDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param user_id
	 * @return
	 * @throws Exception
	 */
	public int delete(long user_id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("user_id", user_id);
		return this.bankDao.deleteModel(paramMap, true);
	}

	/**
	 * 用户绑定银行卡
	 *
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@Override
	public int bindingBank(BankModel model) throws Exception {
		if(model==null){
			FrameUtil.throwBaseException1("请求参数不能为空");
		}
		BankModel bankModel = bankDao.getModelById(model.getUser_id(),true);
		if(bankModel!=null){
			FrameUtil.throwBaseException1("您已经绑过银行卡");
		}

		 bankModel = bankDao.getModelOne(FrameUtil.newHashMap("id_number",model.getId_number().trim()),true);
		if(bankModel!=null){
			FrameUtil.throwBaseException1("该身份证已经绑定过银行卡");
		}

		UserDataModel dataModel = new UserDataModel();
		dataModel.setUser_id(model.getUser_id());
		dataModel.setId_name(model.getId_name());
		dataModel.setId_number(model.getId_number());
		GenderEnum genderEnum = CardNoUtils.getGender(model.getId_number());
		dataModel.setGender(genderEnum.getCode()!=1?0:1);//设置性别
		if(userDataService.update(dataModel)!=1){
			FrameUtil.throwBaseException1("用户信息实名初始化失败");
		}
		//初始化用户信息
        bankDao.insertModel(model,true);

		// 初始化额度申请
		CreditLineApplyModel clam = new CreditLineApplyModel();
		clam.setUser_id(model.getUser_id());
		String limit = SysParamUtil.getValue(Constant.SysParamKeyEnum.CREDIT_LIMIT_MIN);
		clam.setApply_credit_line(Double.parseDouble(limit));
		clam.setApply_time(FrameUtil.getTime());
		clam.setStatus(OrderStatusEnum.INIT.getCode());
		clam.setLast_update_time(FrameUtil.getTime());
		creditLineApplyService.insert(clam);

		return 1;
	}

	@Override
	public void changeBankCard(BankModel newBank) throws Exception {

		// 记录原来的绑卡信息
		BankHistoryModel history = new BankHistoryModel();
		BankModel bankModel = bankDao.getModelById(newBank.getUser_id(), false);
		Assert.notNull(bankModel, "原始银行卡信息不存在");
		BeanUtils.copyProperties(bankModel, history);
		bankModel.setLast_update_time(FrameUtil.getTime());

		/**
		 * Bank_card_number和Bank_mobile都为空表示要解绑
		 * 否则表示需要更换银行卡信息
		 */
		if( StringUtil.isNotEmpty(newBank.getBank_card_number()) && null != newBank.getBank_mobile() ){
			// 换卡时进行4要素验证
			AuthBankModel authModel = new AuthBankModel();
			authModel.setUser_id(bankModel.getUser_id());
			authModel.setBank_card_idname(bankModel.getId_name());
			authModel.setBank_card_idcard(bankModel.getId_number());
			authModel.setBank_card_no(newBank.getBank_card_number());
			authModel.setBank_card_mobile(newBank.getBank_mobile().toString());
			authModel.setReqeust_client("mfq");
			BankCardDataModel bandCard = AuthBankUtils.fourElementsVerify(authModel);

			bankModel.setCertification_channel(bandCard.getCertification_channel());
			newBank.setLast_update_time(bankModel.getLast_update_time());

			bankModel.setWhere_version(bankModel.getVersion());
			bankModel.setBank_card_number(newBank.getBank_card_number());
			bankModel.setBank_mobile(newBank.getBank_mobile());
			bankDao.updateModel(bankModel, true);

			bankHistoryDao.insertModel(history, true);
		}
		// 解绑银行卡
		else if(StringUtil.isEmpty(newBank.getBank_card_number()) && null == newBank.getBank_mobile()){
			bankDao.deleteById(newBank.getUser_id(), true);
			bankHistoryDao.insertModel(history, true);
		}
	}

	@Cacheable(expire = ExpireTime.ONE_DAY)
	@Override
	public List<BankInfoDto> querySupportBankList() throws Exception {
		List<BankInfoDto> remoteBankList = QianKangServer.querySupportBankList();
		if(null == remoteBankList || remoteBankList.size() == 0){
			return Collections.EMPTY_LIST;
		}
		return remoteBankList;
	}


	@Override
	public int updateByMap(Map param) throws Exception {
		return this.bankDao.updateByMap(param,true);
	}

	@Resource
	private IBankDao bankDao;

	@Resource
	private IBankHistoryDao bankHistoryDao;

	@Override
	public IBaseDao getBaseDao() {
		return this.bankDao;
	}

	@Resource
	public IUserDataService userDataService;

	@Resource
	ICreditLineApplyService creditLineApplyService;

}
